package com.example.hello.controller;


import com.example.hello.controller.request.ModifyDrinkRequest;
import com.example.hello.model.Drink;
import com.example.hello.service.IDrinkService;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = "/drink")
//处理/drink这个请求
public class DrinkController {
//    @Autowired
//    private DrinkRepositary drinkRepositary;
    //自动注入repsitory
    @Autowired
    private IDrinkService drinkService;
    @GetMapping("/")
    public List<Drink> getAll(Integer page,Integer limit){
        log.info("拿到了",page,limit);
        PageRequest pageRequest=PageRequest.of(page-1,limit);
        List<Drink> results=drinkService.getAllDrinks(pageRequest).getContent();
        return  results;
    }

    //查询
    //path路径  /drink/1
    @GetMapping("/{id}")
    public Drink getDrink(@PathVariable Integer id){
        log.info("查询的饮品id为: {}",id);
        Drink drink=Drink.builder().id(1).name("茉莉蜜茶").price(Money.parse("USD 4.00")).build();
        return drink;
    }

    //新建
    @PostMapping("/")
    public Drink addNewDrink(@RequestBody @Valid Drink drink, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (ObjectError error:bindingResult.getAllErrors()) {
                log.error(error.toString());
            }
            return null;
        } else {
            log.info("创建新饮品:{}", drink);
            drinkService.addNewDrink(drink);
            return drink;
        }
    }
    // 修改
    // 写一个TO类专门负责传值
    // put /drink/{"id":1,"name":"新奶茶","price",10.00}
    @PutMapping("/")
    public Drink modifyDrink(@RequestBody ModifyDrinkRequest request){
        log.info("要修改的饮品:{}",request);
        //1通过id查找饮品
        Drink drink=drinkService.getDrinkById(request.getId());
//        if (request.getName()!= null && !request.getName().equals(""))
        //覆盖查询出来的原始值 request是新的 drink是查询出来旧的
        BeanUtils.copyProperties(request,drink);
        drinkService.updateDrink(drink);
        return drink;
    }

    // 删除
    // delect /drink/1
    @DeleteMapping("/{id}")
    public String delectDrink(@PathVariable Integer id){
        log.info("要删除的饮品:{}",id);
        drinkService.deleteDrink(id);
        return "删除成功";
    }

    @PostMapping(value = "/upload",consumes = (MediaType.MULTIPART_FORM_DATA_VALUE))
    public String uploadFile(MultipartFile file){
        String dest="D:\\springupload";
        String destFileName=dest+file.getOriginalFilename();
        //读文件
//        file.getInputStream()
        File destFile=new File(destFileName);
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }


    //批量创建饮品
    @PostMapping(value = "/listupload",consumes = (MediaType.MULTIPART_FORM_DATA_VALUE))
    public List<Drink> listuploadFile(MultipartFile file){
        List<Drink> result=new ArrayList<>();
        try {
            BufferedReader reader=new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line="";
            //每次循环都读取一行，不为空就继续往下读
            while ((line=reader.readLine())!=null){
                String[] args=line.split(",");
                Drink drink=Drink.builder()
                        .id(Integer.parseInt(args[0]))
                        .name(args[1])
                        .price(Money.of(CurrencyUnit.of("CNY"),Double.parseDouble(args[2])))
                        .build();
                result.add(drink);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
}
